/* The Application implementation for Emacs.

   For legal stuff see the file COPYRIGHT.  */

#import "EmacsApp.h"

@implementation EmacsApp

/* We're ready to start.  Size the window apropriately and fire up the emacs
   process, possibly editing a file.  */
-appDidInit: sender
{
  id window;

  DPSSetDeadKeysEnabled (DPSGetCurrentContext (), NO);

  window = [currentView window];
  [window setBackgroundGray: NX_WHITE];
  [window removeFromEventMask: NX_KEYUPMASK | NX_FLAGSCHANGEDMASK];
  [window makeFirstResponder: currentView];
  [window setFrameUsingName: "main"];
  [window setFrameAutosaveName: "main"];

  [currentView startEmacs: files : nfiles];

  if (!strcmp (NXGetDefaultValue ([NXApp appName], "NXAutoLaunch"), "YES")
      && !strcmp (NXGetDefaultValue ([NXApp appName],
				     "HideOnAutoLaunch"), "YES"))
    [self hide: self];
  else
    [self appDidUnhide: self];
  [self setDelegate: self];
  return self;
} /* -appDidInit: */

-appDidUnhide: sender
{
#if 0
  int eventChannel;

  evenChannel = [currentView eventChannel];
  if (eventChannel)
    fprintf (eventChannel, "(redraw-display)\n");
#endif
  [[currentView window] makeKeyAndOrderFront: self];
  return self;
} /* -appDidUnhide */

/* Intercept the Quit command and replace it with C-x C-c.  */
-terminate: sender
{
  if (sender && [currentView quitEmacs])
    return self;
  return [super terminate: sender];
} /* -terminate: */

-(BOOL) appAcceptsAnotherFile: sender
{
  return YES;
} /* appAcceptsAnotherFile: */

/* Stash the name of a file in an instance variable so we can give it to the
   child emacs when we fire it up.  */
-(BOOL) app: sender openFile: (const char *) path type: (const char *) type
{
  if ([currentView emacsOn])
    {
      /* If emacs was already running, open file in a new buffer.  */
      return [currentView newFile: path];
    }
  else
    {
      files = realloc (files, (nfiles + 1) * sizeof (char *));
      files[nfiles++] = strcpy (malloc (1 + strlen (path)), path);
    }
  return YES;
} /* -app:openFile:type: */

-currentView
{
  return currentView;
} /* -currentView */

-fontManager
{
  if (!fontManager)
    {
      fontManager = [FontManager new];
      [fontManager setDelegate: self];
    }
  return fontManager;
} /* -fontManager */

-showFontPanel: sender
{
  [[NXApp fontManager] orderFrontFontPanel: self];
  [fontManager setSelFont: [currentView font] isMultiple: NO];
  return self;
} /* -showFontPanel: */

-(BOOL) fontManager: sender willIncludeFont: (const char *) fontName
{
  NXFontMetrics *metrics;
  id font;

  font = [Font newFont: fontName size: (float) 10];
  if (font != nil)
    {
      metrics = [font readMetrics: NX_FONTHEADER];
      if (metrics != NULL)
	return metrics->isFixedPitch;
    }
  return NO;
} /* fontManager:willIncludeFont: */

@end
